<template>
    <div>
        <cus-search>
            <cus-search-item>
                <Form :model="searchForm" :label-width="80">
                    <FormItem label="日期" class="mr_48 mb_20">
                        <cus-datePick :startTime="searchForm.date" :showWeekNum="false" :showShortcuts="false"
                            format="yyyy-MM-dd" @onChange="onChangeDate" :clearable="false"></cus-datePick>
                    </FormItem>
                    <FormItem label="餐段" class="mr_48 mb_20">
                        <Select v-model="searchForm.mealTimes" placeholder="请选择餐段" style="width: 200px;">
                            <Option :value="item.value" v-for="item in mealTimesList" :key="item.value">{{ item.label }}
                            </Option>
                        </Select>
                    </FormItem>
                    <FormItem label="菜肴名称" class="mr_48 mb_20">
                        <Input v-model.trim="searchForm.dishName" placeholder="请输入菜肴名称" style="width: 200px;" clearable
                            maxlength="20"></Input>
                    </FormItem>
                    <FormItem label="伙食单位" class="mr_48 mb_20">
                        <Select style="width: 200px" v-model="searchForm.unitCode">
                            <Option v-for="item in unitList" :key="item.id" :value="item.unitCode">{{ item.unitName }}
                            </Option>
                        </Select>
                    </FormItem>
                    <cusButton size="small" class="mr_10 mb_20" type="primary" @onClick="pageOption.page = 1; onInit();">查询
                    </cusButton>
                    <cusButton size="small" class="mr_10 mb_20" type="primary" ghost @onClick="onReset">重置</cusButton>
                </Form>
            </cus-search-item>
        </cus-search>

        <cus-card class="mt_20">
            <cus-table :border="true" :loading="searchForm.loading" :columns="columns" :data="data" :handleSpan="handleSpan"
                :bottomClass="['cus-page']">
                <template slot-scope="{ row, index }" slot="mealTimes">
                    <span>{{ row.mealTimes == 0 ? '早餐' : row.mealTimes == 1 ? '午餐' : '晚餐' }}</span>
                </template>
                <template slot-scope="{ row, index }" slot="curingState">
                    <span>{{ row.curingState == 0 ? '未完成' : '完成' }}</span>
                </template>
                <template slot-scope="{ row, index }" slot="state">
                    <span>{{ row.state == 0 ? '未完成' : '完成' }}</span>
                </template>
            </cus-table>
            <div style="width: 100%; display: flex; justify-content: flex-end">
                <cus-page :data="pageOption" class="mt_20" @pageChange="onInit"></cus-page>
            </div>
        </cus-card>
        <!-- <cus-footer :showWaterMark="false">
            <div style="width: 100%;display: flex;justify-content: flex-end;padding-right: 20px;">
                <cus-page :data="pageOption" class="mb_10" @pageChange="onInit"></cus-page>
            </div>
        </cus-footer> -->
    </div>
</template>

<script>
import { getSubCanteenList } from "@/api/organ/organization";
import { assignmentPlanningPages, } from '@/api/organ/business';
export default {
    name: 'assignmentPlanning',
    data() {
        return {
            searchForm: {
                loading: false,
                date: new Date().Format('yyyy-MM-dd'),
                mealTimes: 0,
                dishName: '',
                unitCode: '',
            },
            unitList: [],
            data: [],
            mealTimesList: [
                {
                    value: 0,
                    label: '早餐',
                },
                {
                    value: 1,
                    label: '午餐',
                },
                {
                    value: 2,
                    label: '晚餐',
                },
            ],
            columns: [
                {
                    title: '序号',
                    width: 70,
                    key: 'serialNum',
                    // type: 'index',
                    align: 'center'
                },
                {
                    title: '日期',
                    minWidth: 120,
                    key: 'gmtCook',
                    align: 'center'
                },
                {
                    title: '餐段',
                    minWidth: 120,
                    slot: 'mealTimes',
                    align: 'center'
                },
                {
                    title: '烹饪状态',
                    minWidth: 120,
                    slot: 'curingState',
                    align: 'center'
                },
                {
                    title: '菜肴名称',
                    minWidth: 120,
                    key: 'dishName',
                    align: 'center'
                },
                {
                    title: '配料',
                    minWidth: 120,
                    key: 'materialName',
                    align: 'center'
                },
                {
                    title: '切配重量(Kg)',
                    minWidth: 120,
                    key: 'totalWeight',
                    align: 'center'
                },
                {
                    title: '完成状态',
                    minWidth: 120,
                    slot: 'state',
                    align: 'center'
                },
                {
                    title: '出锅量(Kg)',
                    minWidth: 180,
                    key: 'discharge',
                    align: 'center'
                },
            ],
            pageOption: {
                page: 1,
                pageSize: 10,
                pageTotal: 0
            }
        }
    },
    mounted() {
        this.getSubCanteenList();
    },
    methods: {
        onInit() {
            this.onSearch();
            // this.getErrorTempDailyListApi()
        },
        // 重置查询条件·
        onReset() {
            this.resetFilterForm();
            this.onSearch();
        },
        resetFilterForm() {
            this.searchForm.date = new Date().Format('yyyy-MM-dd');
            this.searchForm.mealTimes = 0;
            this.searchForm.dishName = '';
            this.searchForm.unitCode = this.unitList[0].unitCode;
            this.pageOption.page = 1;
        },
        getSubCanteenList() {
            console.log(111);
            getSubCanteenList().then((res) => {
                if (res.code == 1) {
                    this.unitList = res.data.list;
                    this.searchForm.unitCode = res.data.list[0].unitCode;
                    this.onInit();
                }
            });
        },
        // 选择日期变化
        onChangeDate(date) {
            console.log(date);
            this.searchForm.date = date;
            console.log(this.searchForm);
        },
        // 查询作业规划数据
        onSearch() {
            assignmentPlanningPages({
                gmtCook: this.searchForm.date,
                mealTimes: this.searchForm.mealTimes,
                dishName: this.searchForm.dishName,
                org: this.searchForm.unitCode,
                currentPage: this.pageOption.page,
                sizePage: this.pageOption.pageSize,
            }).then((res) => {
                if (res.code === 1) {
                    console.log(res);
                    console.log(this.flattenArray(res.result.records));
                    this.searchForm.loading = false;
                    this.data = this.flattenArray(res.result.records);
                    this.pageOption.pageTotal = res.result.total;
                }
            }).catch((err) => {
                console.log(err);
                // this.tableLoading = false
            })
        },
        // 二维数据降维处理
        flattenArray(inputArray) {
            let result = [];
            let i = 1;
            for (let item of inputArray) {
                let selectItem = { ...item, serialNum: i++ };
                this.flattenItem(selectItem, result);
            }
            return result;
        },
        flattenItem(item, result) {
            let flattenedItem = { ...item };
            if (item.mealJobs && item.mealJobs.length > 0) {
                delete flattenedItem.mealJobs;
                for (let child of item.mealJobs) {
                    result.push({ ...child, ...flattenedItem, });
                    this.flattenItem({ ...child, ...flattenedItem, }, result); // 添加一个指向父级的属性，例如 'parent'
                }
            }
        },
        handleSpan({ row, column, rowIndex, columnIndex }) {
            // console.log(row,column,rowIndex,columnIndex)
            if (columnIndex <= 4 || columnIndex == 8) {
                // console.log(111,'clol');
                const rowspan = this.getRowspan(row, rowIndex);
                // console.log(rowspan);
                if (rowspan >= 1) {
                    return {
                        rowspan,
                        colspan: 1,
                    };
                } else {
                    return {
                        rowspan: 0,
                        colspan: 0,
                    };
                }
            };

        },
        getRowspan(row, rowIndex) {
            const currentName = row.dishName;
            let rowspan = 1; // 默认rowspan为1，也就是每个单元格只占一行
            // 如果当前行不是第一行，则先查看前一行，如果前一行的值（同列单元格）与当前行（同列单元格）相同，则将当前单元格与前一行合并（当前单元格占0行，rowspan=0）
            if (rowIndex > 0) {
                const previousRow = this.data[rowIndex - 1];
                const previousName = previousRow.dishName;
                if (currentName === previousName) {
                    return 0;
                }
            };
            // 然后向后查看，如果后面行（同列单元格）的值与当前行（同列单元格）相同，则每找到一行rowspan加1，直到找到与当前行（同列单元格）的值不同的行为止。（也就是说只能合并连续的行）
            for (let i = rowIndex + 1; i < this.data.length; i++) {
                const nextRow = this.data[i];
                const nextName = nextRow.dishName;
                if (currentName === nextName) {
                    rowspan++;
                } else {
                    break;
                }
            };
            return rowspan;
        },
    }
}
</script>

<style scoped></style>
